import axios from 'axios'
import errors from '@/errors'
import router from '@/router'
import {Notify, Toast} from 'vant'
import VueCookies from 'vue-cookies'


const requests = axios.create({
  timeout: 30 * 1000
})

requests.interceptors.request.use(
  config => {
    Toast.loading({
      message: '加载中...',
      forbidClick: true
    })
    config.headers.Authorization = VueCookies.get('token')
    return config
  },
  error => {
    Toast.clear()
    return Promise.reject(error.response)
  }
)

requests.interceptors.response.use(
  response => {
    Toast.clear()
    return response.data
  },
  error => {
    Toast.clear()
    if (error.response.status === 401) {
      router.replace({
        path: '/login',
        query: {
          path: router.currentRoute.path,
          query: router.currentRoute.query
        }
      })
    } else {
      let exp = error.response.data.detail
      if (Object.hasOwnProperty.call(errors, exp)) {
        Notify(errors[exp])
      }
      return Promise.reject(error.response.data)
    }
  }
)

export default requests
